# app.py
from datetime import time
from encodings.punycode import T
import urllib3
from flask import Flask, request, jsonify
from flask_cors import CORS
import json
import threading

from service.DownloadHuiwuFile import DownloadHuiwuFile
from service.GetZrksTxt import GetZrksTxt
from service.UpdateHuiwuDoc import UpdateHuiwuDoc
from service.CheckIfUpdateFile import CheckIfUpdateFile
from service.UpdateOaDoc import UpdateOaDoc
from service.MonitorHuiwu import MonitorHuiwu

app = Flask(__name__)
CORS(app)

# 禁用SSH警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# 减少读写操作，使用内存缓存
old_data = None
titles = []
monitor_instance = MonitorHuiwu(60*1)

@app.before_first_request
def startup_once():
    
    print("⚙️ 收文小助手启动成功 ⚙️ （最后一次更新时间：2025.11.19，开发者：温绍杰，微信：ShawJ1030）")
    

# 首页路由，返回前端页面
@app.route('/')
def index():
    return app.send_static_file('index2.html')
    
@app.route('/update/huiwu/doc', methods=['POST'])
def update_huiwu_doc():
    data = request.get_data().decode('utf-8')
    data = json.loads(data)
    # 更新文件（直接传cookie）
    update_doc = UpdateHuiwuDoc(data['huiwu_cookie'], data['oa_cookie'], data['pageNum'], data['isAuto'], data['mode'])
    if update_doc.doUpdate():
        CheckIfUpdateFile().updateCheckTime()
        return jsonify({"status": "success"})
    else:
        return jsonify({"status": "error"})

@app.route('/update/oa/doc', methods=['POST'])
def update_oa_doc():
    data = request.get_data().decode('utf-8')
    data = json.loads(data)
    update_doc = UpdateOaDoc(data['oa_cookie'], data['pageNum'], data['isAuto'])
    if update_doc.doUpdate():
        return jsonify({"status": "success"})
    else:
        return jsonify({"status": "error"})

@app.route('/download/huiwuFile', methods=['POST'])
def download_huiwuFile():
    data = request.get_data().decode('utf-8')
    data = json.loads(data)
    # 检查是否需要更新文件
    if_update_file = CheckIfUpdateFile().doCheck()
    download_huiwuFile = DownloadHuiwuFile(data['huiwu_cookie'], data['rKey'], data['fileTitle'])
    if download_huiwuFile.doDownload():
        return jsonify({"status": "success", "if_update_file": if_update_file})
    else:
        return jsonify({"status": "error"})
    
@app.route('/getdata/zrks', methods=['POST'])
def get_zrksTxt():
    data = request.get_data().decode('utf-8')
    data = json.loads(data)
    if data['zrks'] == "":
        return jsonify({"status": "success", "zrks_txt": ''})
    zrks_txt = GetZrksTxt(data['zrks']).doGet()
    if zrks_txt:
        return jsonify({"status": "success", "zrks_txt": zrks_txt})
    else:
        return jsonify({"status": "error"})
    
@app.route('/getdata/zrks/codeName', methods=['GET'])
def get_zrksCodeName():
    zrks_codeName = GetZrksTxt('').getZrksCodeName()
    if zrks_codeName:
        return jsonify({"status": "success", "zrks_codeName": zrks_codeName})
    else:
        return jsonify({"status": "error"})


@app.route('/monitor/huiwu', methods=['POST'])
def start_monitorHw():
    data = request.get_data().decode('utf-8')
    data = json.loads(data)
    # if monitor_instance.getStatus():
    #     return jsonify({"monitorHw": "running", "status": "warning"})
    monitor_instance.start_monitoring(data['huiwu_cookie'], data['initRkey']) # 启动监控线程
    return jsonify({"monitorHw": "running", "status": "success"})

@app.route('/monitor/setMails', methods=['POST'])
def set_monitorMail():
    data = request.get_data().decode('utf-8')
    data = json.loads(data)
    monitor_instance.setMail(data['mails'])
    return jsonify({"status": "success"})

@app.route('/monitor/getMails', methods=['GET'])
def get_monitorMail():
    mails = monitor_instance.getMails()
    return jsonify({"status": "success", "receiver_list": mails})

if __name__ == '__main__':
    app.run(debug=True, port=7788)